package com.dayuan.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dayuan.bean.BackUser;
import com.dayuan.service.AdminUserService;
import com.dayuan.utils.PatternUtils;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Resource
	private AdminUserService adminUserService;

	// 登录页面
	@RequestMapping(value = "/hello.shtml", method = { RequestMethod.POST, RequestMethod.GET })
	public String hello() {
		return "login";
	}

	// 验证帐号密码
	@RequestMapping(value = "/check.shtml", method = { RequestMethod.POST, RequestMethod.GET })
	public String check(HttpSession session, ModelMap modelMap, String userId, String passWord) throws Exception {
		try {

			if (passWord == null || userId == null || "".equals(userId) || "".equals(passWord)) {
				modelMap.addAttribute("msg", "帐号密码不能为空");
				return "redirect:hello.shtml";
			}

			// shiro start
			UsernamePasswordToken token = new UsernamePasswordToken(userId, passWord);
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
			// shiro end

			// 登陆成功把用户信息放进session
			BackUser adminUser = new BackUser();
			if (PatternUtils.isEmail(token.getUsername())) {
				adminUser.setEmail(token.getUsername());
			} else {
				adminUser.setUserName(token.getUsername());
			}

			BackUser result = adminUserService.selectAdminUser(adminUser);

			List<Integer> rid = adminUserService.selectUserRole(result.getId());
			for (Integer integer : rid) {
				if (result.getReview() == 0 && integer == 2) {
					modelMap.addAttribute("msg", "等待商家审核");
					return "redirect:hello.shtml";
				} else if (result.getReview() == 1 && integer == 2) {
					modelMap.addAttribute("msg", "没有权限登录，请联系管理员");
					return "redirect:hello.shtml";
				}
			}

			return "redirect:/home/jump.shtml";

		} catch (AuthenticationException e) {

			modelMap.addAttribute("msg", "账号密码错误");
			return "redirect:hello.shtml";
		} catch (Exception e) {
			e.printStackTrace();
			modelMap.addAttribute("msg", "网络错误");
			return "redirect:hello.shtml";
		}

	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/logout.shtml", method = { RequestMethod.POST, RequestMethod.GET })
	public String logout(HttpSession session) {
		session.removeAttribute("adminUser");
		return "login";
	}

}